<template>
	<view class="file-wrap bg-white">
		<view class="file-list" v-if="fileList">
			<view class="file-item bbc" v-for="(item,index) in fileList" :key="index">
				<view class="img-box">
					<image class="img" v-if="getFileType(item[option.id])" :src="$Common.getFileUrl(item[option.id])"
						mode="aspectFill"></image>
					<image class="img" v-else src="../../static/application/file_img.png" mode="aspectFill"></image>
				</view>
				<view class="img-info">
					<view class="name">{{item[option.name]||'名称'}}</view>
					<view class="tips">{{sizeTostr((item[option.size] || 0))}}</view>
				</view>
				<view class="file-tool" @click="onSelFile(item,index)">
					<image style="width: 60rpx;height: 60rpx;" src="../../static/tool.png" mode=""></image>
				</view>
			</view>
		</view>
		<!-- 文件菜单 -->
		<u-action-sheet @select="onSelectClick" @close="fileToolShow=false" :actions="list" :closeOnClickOverlay="true"
			:closeOnClickAction="true" :show="fileToolShow"></u-action-sheet>
	</view>

</template>

<script>
	export default {
		props: {
			option: {
				default: {
					id: 'fileId',
					size: 'fileSize',
					name: 'fileName'
				},
				type: Object
			},
			fileList: {
				type: Array,
				default: []
			}
		},
		data() {
			return {
				list: [{
					name: '预览',
				}],
				fileToolShow: false,
				showPopupFile: false,
				count: 10,
				selCurrent: null
			}
		},

		mounted() {
			console.log('===>', this.fileList)
		},
		methods: {
			checkImg(url) {
				var index = url.indexOf("."); //（考虑严谨用lastIndexOf(".")得到）得到"."在第几位
				let img_id = url.substring(index); //截断"."之前的，得到后缀
				if (img_id != ".bmp" && img_id != ".png" && img_id != ".gif" && img_id != ".jpg" && img_id !=
					".jpeg") { //根据后缀，判断是否符合图片格式
					return false
				}
				return true
			},
			checkTv(url) {
				var index = url.indexOf("."); //（考虑严谨用lastIndexOf(".")得到）得到"."在第几位
				let tv_id = url.substring(index); //截断"."之前的，得到后缀
				if (tv_id != ".mp4" && tv_id != ".rmvb" && tv_id != ".avi" && tv_id != ".ts") { //根据后缀，判断是否符合视频格式
					return false
				}
				return true
			},
			getFileType(path) {
				
				if (path && (this.checkImg(path) || this.checkTv(path))) {
					return true
				} else {
					return false
				}
			},
			onSelectClick(item) {
				let _this = this
				if (item.name == '预览') {
					let file = this.fileList[this.selCurrent];
					let pathUrl = file[this.option.id];
					if (this.getFileType(pathUrl)) {
						let url = pathUrl ? this.$Common.getFileUrl(pathUrl) : ''
						wx.previewMedia({
							sources: [{
								url: url
							}, ],
							success: function(res) {
								console.log(res)
							}
						})
					} else {
						wx.downloadFile({
							url: this.$Common.getFileUrl(file[this.option.id]),
							success: function(res) {
								const filePath = res.tempFilePath
								wx.openDocument({
									filePath: filePath,
									success: function(res) {
										console.log('打开文档成功')
									}
								})
							},
							fail: function(er) {
								_this.$Msg.Toast('查看失败', er)
							}
						})

					}
				} else {
					// 删除
					this.fileList.splice(this.selCurrent, 1)
				}
				this.fileToolShow = false
			},
			onSelFile(item, index) {
				this.selCurrent = index
				this.fileToolShow = true
			},
			fnShowPopupFile() {
				if (this.count - this.fileList.length == 0) {
					this.$Msg.Toast('只能选择10个文件')
					return
				}
				this.showPopupFile = true
			},
			onItem(type) {
				if (type == 'file') {
					// 消息选择文件
					this.chooseMessageFile()
				} else {
					this.chooseImage(type)
				}
				this.showPopupFile = false
			},
			open() {

			},
			chooseImage(type) {
				let self = this;
				uni.chooseMedia({
					count: this.count - this.fileList.length,
					sizeType: ['compressed'],
					mediaType: 'mix',
					sourceType: [type],
					success: function(res) {
						self.matFile(res.tempFiles || res.tempFilePaths)
					},
					fail: function(er) {
						// self.$M sg.Toast('选择失败:' + er)
					}
				})
			},
			chooseMessageFile() {
				let _this = this
				wx.chooseMessageFile({
					count: this.count - this.fileList.length,
					type: 'file',
					success(res) {
						_this.matFile(res.tempFiles)
					},
					fail(er) {
						console.log(er)
					}
				})
			},
			sizeTostr(size) {
				var data = "";
				if (size < 0.1 * 1024) { //如果小于0.1KB转化成B  
					data = size.toFixed(2) + "B";
				} else if (size < 0.1 * 1024 * 1024) { //如果小于0.1MB转化成KB  
					data = (size / 1024).toFixed(2) + "KB";
				} else if (size < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB  
					data = (size / (1024 * 1024)).toFixed(2) + "MB";
				} else { //其他转化成GB  
					data = (size / (1024 * 1024 * 1024)).toFixed(2) + "GB";
				}
				var sizestr = data + "";
				var len = sizestr.indexOf("\.");
				var dec = sizestr.substr(len + 1, 2);
				if (dec == "00") { //当小数点后为00时 去掉小数部分  
					return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
				}
				return sizestr;
			},
			onUploadItem(item) {
				let _this = this
				uni.showModal({
					title: '需要重新上传吗？',
					cancelText: '取消',
					success(e) {
						if (e.confirm) {
							item.status = 'uploading'
							_this.$Net.upload(item.tempFilePath || item.path, 0).then(result => {
								if (!result.success) {
									item.status = 'fail'
								}
								item.url = result.body
								item.status = 'success'
							})

						}
					}
				})
			},
			async matFile(filePaths, fileType = 'img') {
				let lists = [].concat(filePaths)
				let fileListLen = this[`fileList`].length
				lists.map((item, index) => {
					console.log('file=>', item)
					this[`fileList`].push({
						url: '',
						tempFilePath: item.tempFilePath || item.path,
						status: 'uploading',
						message: '上传中',
						type: item.fileType,
						size: this.sizeTostr((item.size || 0)),
						fileSize: item.size || 0,
						fileName: item.name || ('图片' + (fileListLen + 1))
					})
				})
				for (let i = 0; i < lists.length; i++) {
					let status = 'success'
					let result = await this.$Net.upload(lists[i].tempFilePath || lists[i].path, 0);
					// result.success = false
					if (!result.success) {
						status = 'fail'
					}
					let item = this.fileList[fileListLen]
					this.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: status,
						message: '',
						size: this.sizeTostr((item.fileSize || 0)),
						fileSize: item.fileSize || 0,
						fileName: item.name || ('图片' + (fileListLen + 1)),
						dateTime: uni.$u.timeFormat(this.timestamp, 'yyyy-mm-dd hh:MM'),
						url: result.body,
					}))
					fileListLen++
				}
				this.$emit('change', this.fileList)
			},
		}
	}
</script>
<style scoped lang="scss">
	.file-wrap {
		position: relative;
		width: calc(100vw - 64rpx);
		margin-left: 32rpx;

		// margin-top: 20rpx;
		// background-color: red;
		.upload-img {
			position: absolute;
			right: 24rpx;
			top: -42rpx;
		}

		.file-list {
			width: 100%;
			display: block;

			.file-item {
				display: flex;
				align-items: center;
				padding: 10rpx 0;
				margin-top: 20rpx;

				&:last-of-type {
					border-bottom: none;
				}

				.img-box {
					width: 64rpx;
					height: 64rpx;
					border-radius: 10%;
					overflow: hidden;
					position: relative;

					.icon {
						position: absolute;
						left: 0;
						top: 0;
						z-index: 1;
						width: 64rpx;
						height: 64rpx;
						padding: 8rpx;
						box-sizing: border-box;
						background-color: rgba(#000, .2);

						.uploading {
							animation: wait 4s infinite;
						}
					}

					.img {
						width: 100%;
						height: 100%;
						position: relative;
						z-index: 0;
					}

				}

				.img-info {
					flex: 1;
					width: 0;
					margin-left: 20rpx;

					.name {
						width: 100%;
						word-break: break-all;
						font-size: 30rpx;
						font-weight: 400;
						color: #323233;
					}

					.tips {
						font-size: 24rpx;
						font-weight: 400;
						color: #A4A7B3;
					}
				}

				.file-tool {
					width: 100rpx;
					height: 100%;
					display: flex;
					align-items: center;
					justify-content: flex-end;
				}
			}
		}
	}

	@keyframes wait {
		100% {
			transform: rotate(360deg);
		}
	}

	.popup-file-wrap {
		width: 511rpx;
		height: 628rpx;
		background: #FFFFFF;
		border-radius: 20rpx;
		overflow: hidden;

		.popup-header {
			height: 187rpx;
			background: #EBF0FF;
			border-radius: 20rpx 20rpx 0px 0px;
			display: flex;
			align-items: center;
			padding: 0 42rpx;
		}

		.popup-content {
			padding: 40rpx 42rpx;

			.cell {
				padding: 20rpx 0;
				border-bottom: 1px solid rgba(204, 204, 204, .2);
			}
		}

		.popup-btn {
			::v-deep button {
				width: 427rpx;
				border-radius: 100rpx;
			}
		}


	}
</style>
